from PyQt5.QtCore import QThread, pyqtSignal

from base_api.base.MessageClass import Message

"""
信号类
"""


class PyqtThreadPool(QThread):
    signal = pyqtSignal(object)
    signal_2 = pyqtSignal(object)
    signal_3 = pyqtSignal(object)
    signal_4 = pyqtSignal(object)
    signal_5 = pyqtSignal(object)
    # False表示对应信号位未被占用
    signal_flag_list = [False, False, False, False, False]
    # 信号位队列
    # signal_list = [signal, signal_2, signal_3, signal_4, signal_5]

    def __init__(self):
        super().__init__()
        # 待执行的线程任务
        self.run_task = None
        # 当前占用的信号位
        self.signal_this = None
        # 当前占用的信号位 对应索引
        self.signal_this_index = -1

    def get_signal(self):
        # 所有信号位标志都为True，表示均被占用
        if all(self.signal_flag_list):
            return
        if not self.signal_flag_list[0]:
            self.signal_this = self.signal
            self.signal_this_index = 0
        elif not self.signal_flag_list[1]:
            self.signal_this = self.signal_2
            self.signal_this_index = 1
        elif not self.signal_flag_list[2]:
            self.signal_this = self.signal_3
            self.signal_this_index = 2
        elif not self.signal_flag_list[3]:
            self.signal_this = self.signal_4
            self.signal_this_index = 3
        elif not self.signal_flag_list[4]:
            self.signal_this = self.signal_5
            self.signal_this_index = 4
        self.signal_flag_list[self.signal_this_index] = True

    def run(self):
        try:
            self.run_task()
        except Exception as e:
            self.output(Message(status=-3, data=str(e)))
        finally:
            # 运行完毕
            self.signal_flag_list[self.signal_this_index] = False
            self.signal_this_index = -1
            # 结束
            self.output(Message(status=-1, data=''))

    def output(self, msg: Message):
        self.signal_this.emit(msg)

